import type { Settings as LayoutSettings } from '@ant-design/pro-layout';
import { SettingDrawer } from '@ant-design/pro-layout';
import { PageLoading } from '@ant-design/pro-layout';
import type { RunTimeLayoutConfig } from 'umi';
import { history, Link, RequestConfig } from 'umi';
import { RequestOptionsInit } from 'umi-request';
import RightContent from '@/components/RightContent';
import Footer from '@/components/Footer';
import { BookOutlined, LinkOutlined } from '@ant-design/icons';
import {
  currentUser as queryCurrentUser,
  publicKey as queryPublicKey,
} from './services/ant-design-pro/api';

import * as Storage from './services/storage';
import JSEncrypt from 'jsencrypt';

import defaultSettings from '../config/defaultSettings';

import { encrypt, decrypt } from './services/security';

const isDev = process.env.NODE_ENV === 'development';
const loginPath = '/user/login';
let jsEncrypt: JSEncrypt;

/** 获取用户信息比较慢的时候会展示一个 loading */
export const initialStateConfig = {
  loading: <PageLoading />,
};

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  currentUser?: API.CurrentUser;
  loading?: boolean;
  fetchUserInfo?: () => Promise<API.CurrentUser | undefined>;
}> {
  const fetchPublicKey = async () => {
    try {
      const msg = await queryPublicKey();
      return msg.data;
    } catch (error) {
      history.push(loginPath);
    }
    return '';
  };

  const fetchUserInfo = async () => {
    try {
      const msg = await queryCurrentUser();
      return msg.data;
    } catch (error) {
      history.push(loginPath);
    }
    return undefined;
  };

  // --- begin ---
  let publicKey: string = await fetchPublicKey();
  if (jsEncrypt === null || jsEncrypt === undefined) {
    jsEncrypt = new JSEncrypt();
  }
  jsEncrypt.setPublicKey(publicKey);

  Storage.setItem(Storage.KEY_PUBLIC, publicKey);
  Storage.setItem(Storage.KEY_CRYPTO, '0987654321654321');
  Storage.setItem(Storage.KEY_IV, '1234567890123456');
  // --- end ---

  // 如果不是登录页面，执行
  if (history.location.pathname !== loginPath) {
    const currentUser = await fetchUserInfo();
    return {
      fetchUserInfo,
      currentUser,
      settings: defaultSettings,
    };
  }

  return {
    fetchUserInfo,
    settings: defaultSettings,
  };
}

// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({ initialState, setInitialState }) => {
  return {
    rightContentRender: () => <RightContent />,
    disableContentMargin: false,
    waterMarkProps: {
      content: initialState?.currentUser?.name,
    },
    footerRender: () => <Footer />,
    onPageChange: () => {
      const { location } = history;
      // 如果没有登录，重定向到 login
      if (!initialState?.currentUser && location.pathname !== loginPath) {
        history.push(loginPath);
      }
    },
    links: isDev
      ? [
          <Link key="openapi" to="/umi/plugin/openapi" target="_blank">
            <LinkOutlined />
            <span>OpenAPI 文档</span>
          </Link>,
          <Link to="/~docs" key="docs">
            <BookOutlined />
            <span>业务组件文档</span>
          </Link>,
        ]
      : [],
    menuHeaderRender: undefined,
    // 自定义 403 页面
    // unAccessible: <div>unAccessible</div>,
    // 增加一个 loading 的状态
    childrenRender: (children, props) => {
      // if (initialState?.loading) return <PageLoading />;
      return (
        <>
          {children}
          {!props.location?.pathname?.includes('/login') && (
            <SettingDrawer
              disableUrlParams
              enableDarkTheme
              settings={initialState?.settings}
              onSettingChange={(settings) => {
                setInitialState((preInitialState) => ({
                  ...preInitialState,
                  settings,
                }));
              }}
            />
          )}
        </>
      );
    },
    ...initialState?.settings,
  };
};

function setHeaders(secretKey: string, secretIv: string, token: string | null): any {
  let headers = {
    'Content-Type': 'application/json;charset=utf-8',
    CRYPTO: secretKey,
    IV: secretIv,
    token: '',
  };
  if (token) {
    headers = { ...headers, token: Storage.TOKEN_PREFIX + token };
  }
  return headers;
}

const requestInterceptor = (url: string, options: RequestOptionsInit) => {
  if (url === '/icloud/common/public-key') {
    const headers = { 'Content-Type': 'application/json;charset=utf-8' };
    return {
      url,
      options: { ...options, interceptors: true, headers },
    };
  }

  const crypto = Storage.getItem(Storage.KEY_CRYPTO);
  const iv = Storage.getItem(Storage.KEY_IV);
  const token = Storage.getItem(Storage.KEY_TOKEN);
  const secretKey = jsEncrypt.encrypt(crypto) as string;
  const secretIv = jsEncrypt.encrypt(iv) as string;
  const headers = setHeaders(secretKey, secretIv, token);
  const text = options.data ? encrypt(crypto, iv, JSON.stringify(options.data)) : '';

  //console.log('headers:', crypto, iv, token, secretKey, secretIv, text);

  return {
    url: `${url}`,
    options: { ...options, data: text, interceptors: true, headers },
  };
};

const responseInterceptor = async (resp: Response, options: RequestOptionsInit): Promise<any> => {
  const { url } = resp;
  if (url.indexOf('/icloud/common/public-key') !== -1) {
    return resp;
  }

  const crypto = Storage.getItem(Storage.KEY_CRYPTO);
  const iv = Storage.getItem(Storage.KEY_IV);
  //const token = Storage.getItem(Storage.KEY_TOKEN);
  //const secretKey = jsEncrypt.encrypt(crypto) as string;
  //const secretIv = jsEncrypt.encrypt(iv) as string;

  let respJson = await resp.clone().json();
  const data = decrypt(crypto, iv, respJson.data);
  respJson = { ...respJson, data };
  console.log('resp:', respJson);

  return respJson;
};

export const request: RequestConfig = {
  timeout: 3000,
  errorConfig: {
    adaptor: (resData) => {
      return {
        ...resData,
        errorCode: resData.code,
        errorMessage: resData.message,
      };
    },
  },
  middlewares: [],
  requestInterceptors: [requestInterceptor],
  responseInterceptors: [responseInterceptor],
};
